import 'dart:math';

import 'package:flutter/widgets.dart';

/// 水印画布
class WatermarkPainter extends CustomPainter {
  WatermarkPainter({required this.content});

  final String content;
  final Color color = const Color.fromRGBO(204, 204, 204, 0.5);

  final gapX = 40; // 左右间隔
  final gapY = 20; // 上下间隔

  @override
  void paint(Canvas canvas, Size size) {
    final textPainter = TextPainter(
      text: TextSpan(
        text: content,
        style: TextStyle(
          fontSize: 20,
          color: color,
        ),
      ),
      textDirection: TextDirection.ltr,
    );

    textPainter.layout();

    final height = size.height;
    final width = size.width;
    final maskWidth = textPainter.width;
    final maskHeight = textPainter.height;

    // 计算水印对角线长度
    final diagonal = sqrt(maskWidth * maskWidth + maskHeight * maskHeight);

    for (var y = -diagonal; y < height + diagonal; y += gapY + diagonal) {
      for (var x = -diagonal; x < width + diagonal; x += gapX + diagonal) {
        canvas.save();
        canvas.translate(x, y);
        canvas.rotate(-0.45); // 旋转水印
        textPainter.paint(canvas, Offset.zero);
        canvas.restore();
      }
    }
  }

  @override
  bool shouldRepaint(covariant CustomPainter oldDelegate) {
    return false;
  }
}
